// pages/total/total.js
Page({
  data: {
    globalData: getApp().globalData,
    address: {},
    list: [],
    totalPrices: 0
  },

  onLoad(options) {
    this.setData({list: JSON.parse(options.list)})
    let total = 0
    this.data.list.forEach(item => {total += item.reprice * item.count})
    this.setData({totalPrices: total + 6})
  },
  onShow(options) {
    this.getAddress()
  },

  getAddress() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/address/query',
      method: 'GET',
      data: {
        userId: wx.getStorageSync('user').userId,
        isDefault: true
      },
      success(res) {
        if(res.data.data.length == 0) {
          wx.showModal({
            title: '提示',
            content: '请先添加收货地址',
            complete: (res) => {
              if (res.confirm) {
                wx.navigateTo({url: '/pages/addAddr/addAddr',})
              } else if (res.cancel) {
                wx.navigateBack()
              }
            }
          })
        } else {
          that.setData({
            address: res.data.data[0]
          })
        }
      } 
    })
  },
  toAddress() {
    wx.navigateTo({url: '/pages/address/address'})
  },
  submit() {
    this.delItems()
    wx.showModal({
      title: '微信支付',
      content: '茶都商城\n￥' + this.data.totalPrices.toFixed(2),
      complete: (res) => {
        if (res.cancel) {
          this.addOrder(1)
          wx.navigateTo({url: '/pages/order/order?status=' + 1})
        }
        if (res.confirm) {
          this.addOrder(2)
          wx.navigateTo({url: '/pages/order/order?status=' + 2})
        }
      }
    })
  },
  addOrder(status) {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/order',
      method: 'POST',
      data: {
        userId: wx.getStorageSync('user').userId,
        addressId: that.data.address.addressId,
        paymentMoney: that.data.totalPrices,
        status: status,
        paymentTime: status === 2 ? new Date() : '',
        items: that.data.list  
      },
      success(res) {
        if(res.data.code === 1) {
          console.log('success');
        }
      }
    })
  },
  delItems() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/cart/dels',
      data: {
        userId: wx.getStorageSync('user').userId,
        done: 1
      },
      method: 'DELETE',
      success(res) {
        that.getCarts()
      }
    })
  },
  
})